package com.cedric.yixianpai.server.Utils;

import com.cedric.yixianpai.game.interfaces.Card;
import com.cedric.yixianpai.server.config.MyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@ComponentScan("com.cedric.yixianpai.cards")
public class CardFactory {
    private final Map<String, Class<? extends Card>> cardTypes;
    private final List<CardInfoDTO> cardInfos;

    public CardFactory() {
        cardTypes = new HashMap<>();
        cardInfos = new ArrayList<>();
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        String[] beanNames = applicationContext.getBeanNamesForType(Card.class);
        //使用Component注解获取name与class
        for (String beanName : beanNames) {
            Object bean = applicationContext.getBean(beanName);
            if (bean instanceof Card) {
                cardTypes.put(beanName, (Class<? extends Card>) bean.getClass());
                Card card = (Card) bean;
                CardInfoDTO cardInfo = new CardInfoDTO(beanName,card.getTitle(), card.getSect(), card.getPeriod(), card.getDescription());
                cardInfos.add(cardInfo);
            }
        }
//        cardTypes.put("化灵诀", HuaLingJue.class);
//        cardTypes.put("暗鸦灵剑", AnYaLingJian.class);
//        cardTypes.put("巨虎灵剑", JuHuLingJian.class);
        // 添加更多卡牌类型...
    }

    public Card createCard(String classtype, int lvl) throws NoSuchMethodException {
        Class<? extends Card> cardClass = cardTypes.get(classtype);
        if (cardClass != null) {
            try {
                return cardClass.getDeclaredConstructor(int.class).newInstance(lvl);
            } catch (Exception e) {
                throw new RuntimeException("Error creating card instance", e);
            }
        } else {
            throw new IllegalArgumentException("Invalid card type: " + classtype);
        }
    }

    public List<CardInfoDTO> getCards() {
        return cardInfos;
    }
}